import React from 'react';
import * as _ from 'lodash';
import { Button, Icon, Modal, message, Checkbox, Pagination } from 'antd';
import { WeaTools, WeaLocaleProvider, WeaUpload, WeaTab } from 'ecCom';
import { WeaForm } from 'comsMobx';

const getLabel = WeaLocaleProvider.getLabel;

class MaterialLibRight extends React.Component {
    state = { data: [], pageCurrent: 1, pageSize: 10, pageTotal: 0, checkedFiles: [], edit: false, file: {}, isPanelShow: false, form: new WeaForm(), searchKey: '', condition: [] };

    constructor(props) {
        super(props);
        this.onUploading = this.onUploading.bind(this);
        this.getFiles = this.getFiles.bind(this);
        this.onPageCurrentChange = this.onPageCurrentChange.bind(this);
        this.onPageSizeChange = this.onPageSizeChange.bind(this);
        this.onCheckAll = this.onCheckAll.bind(this);
        this.onCheck = this.onCheck.bind(this);
        this.onEdit = this.onEdit.bind(this);
        this.onChange = this.onChange.bind(this);
        this.onSave = this.onSave.bind(this);
        this.onDelete = this.onDelete.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.getCheckedFiles = this.getCheckedFiles.bind(this);
        this.imageCarousel = this.imageCarousel.bind(this);
        this.initForm = this.initForm.bind(this);
    }

    componentDidMount() {
        this.initForm();
    }

    componentWillMount() {
        this.getFiles(this.props.dir);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.dir != this.props.dir) {
            const { form } = this.state;
            form.resetForm();
            this.updateInputValue('');
            this.getFiles(nextProps.dir);
        }
    }

    componentDidUpdate() {
        const input = this.refs.input;
        input && input.focus();
    }


    // 图片放大轮播
    imageCarousel(imgObj, e) {
        const { isShow } = this.props;
        if (!isShow) return;
        let imgPool = [];
        let indexNum = 0;
        jQuery('.portal-p4e-mlt-img').each(function () {
            const imgsrc = jQuery(this).attr('data-imgsrc') ? jQuery(this).attr('data-imgsrc') : jQuery(this).attr('src');
            imgPool.push(imgsrc);
        });
        let imgsrc = jQuery(e.target).attr('src');

        for (let i = 0; i < imgPool.length; i++) {
            if (imgsrc == imgPool[i]) {
                indexNum = i;
                break;
            }
        }
        if (window.IMCarousel) {
            window.IMCarousel.showImgScanner4Pool(true, imgPool, indexNum, null, window.top);
        } else {
            load(['/social/js/drageasy/drageasy.js', '/social/js/bootstrap/js/bootstrap.js?v=20171218', '/social/im/js/IMUtil_wev8.js', '/social/js/imcarousel/imcarousel.js'], 'imcarouselJS', () => {
                window.IMCarousel.showImgScanner4Pool(true, imgPool, indexNum, null, window.top);
            });
        }
    }

    render() {
        const { hasRight, dir, multiCheck = false } = this.props;
        const { data = [], pageCurrent, pageSize, pageTotal, checkedFiles, edit, file, isPanelShow, form, searchKey } = this.state;
        const checkedCount = checkedFiles.length;
        const checkedAll = (checkedCount == data.length) && (data.length > 0);
        const disabled = checkedCount == 0;

        let row = [],
col = [];
        for (let i = 0, len = data.length; i < len; i++) {
            col.push(data[i]);
            if (i % 5 == 4 || i == len - 1) {
                row.push(col);
                col = [];
            }
        }
        return (
            <div className="portal-p4e-mlr">
                {
                    hasRight ? (
                            <div className="portal-p4e-mlr-top">
                                {
                                    multiCheck && (
                                        <div className="portal-p4e-mlr-chk">
                                            <Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@jq1j19`} checked={checkedAll} onChange={e => this.onCheckAll(e.target.checked)}>{getLabel(131965, '全选')}</Checkbox>
                                        </div>
                                    )
                                }
                                <div className="portal-p4e-mlr-btns" style={{ position: 'absolute', right: '350px' }}>
                                    <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@3ox9sz`}
                                      uploadId="uploadFile"
                                      uploadUrl={`/api/portal/materialLib/uploadFile?dir=${dir}`}
                                      category="string"
                                      multiSelection={true}
                                      maxUploadSize={100}
                                      showClearAll={false}
                                      autoUpload={true}
                                      limitType="jpg,jpeg,gif,ico,bmp,png,flv,mp3,swf,mp4,wmv,ogg,webm"
                                      onUploading={this.onUploading}
                                      onChange={() => this.getFiles(dir)}
                                      style={{ display: 'inline-block', paddingTop: 0 }}
                                    >
                                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lmz1fq`} type="primary" className="portal-p4e-mlr-btn">
                                            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@n7zr7n`} type="plus" />
                                        </Button>
                                    </WeaUpload>
                                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@r88p37`}
                                      type="primary"
                                      disabled={disabled}
                                      className="portal-p4e-mlr-btn"
                                      style={disabled ? { backgroundColor: '#d8d8d8', zIndex: '999' } : { zIndex: '999' }}
                                      onClick={() => this.onBatchDelete()}
                                    >
                                        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@xesbvs`} type="minus" />
                                    </Button>
                                </div>
                                        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@dbbsfq`}
                                          datas={[]}
                                          showSearchAd={isPanelShow}
                                          setShowSearchAd={bool => this.setPanelStatus(bool)}
                                          hideSearchAd={() => this.setPanelStatus(false)}
                                          searchType={['base', 'advanced']}
                                          buttonsAd={this.getTabButtonsAd()}
                                          style={{ marginTop: '-7px', height: '47px' }}
                                          searchsAd={
                                        form.render(
                                            {},
                                            { onChange: (v) => {
                                                    if (v.filename) {
                                                        this.updateInputValue(v.filename.value);
                                                    }
                                                },
                                                onEnterSearch: () => { this.getFiles(); this.setPanelStatus(false); },
                                            },
                                        )
                                    }
                                          searchsBaseValue={searchKey}
                                          onSearch={() => this.onPageCurrentChange(1)}
                                          onSearchChange={(v => this.updateInputValue(v))}
                                        />
                            </div>
                        ) : (
                        <div className="portal-p4e-mlr-top">
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@zvzqa4`}
                              datas={[]}
                              showSearchAd={isPanelShow}
                              setShowSearchAd={bool => this.setPanelStatus(bool)}
                              hideSearchAd={() => this.setPanelStatus(false)}
                              searchType={['base', 'advanced']}
                              buttonsAd={this.getTabButtonsAd()}
                              style={{ marginTop: '-7px', height: '47px' }}
                              searchsAd={
                                    form.render(
                                        {},
                                        { onChange: (v) => {
                                                if (v.filename) {
                                                    this.updateInputValue(v.filename.value);
                                                }
                                            },
                                            onEnterSearch: () => { this.getFiles(); this.setPanelStatus(false); },
                                        },
                                    )
                                }
                              searchsBaseValue={searchKey}
                              onSearch={() => this.onPageCurrentChange(1)}
                              onSearchChange={(v => this.updateInputValue(v))}
                            />
                        </div>
                    )
                }

                <div className="portal-p4e-mlr-middle">
                    {
                        row && row.length ? (
                                <div className="portal-p4e-mlt-table">
                                    {
                                        row.map((row, index) => (
                                                <ul key={index} className="portal-p4e-mlt-tr">
                                                    {
                                                        row.map((col) => {
                                                            const checked = _.findIndex(checkedFiles, item => item.id == col.id) != -1;
                                                            return (
                                                                <li key={col.id} className="portal-p4e-mlt-td">
                                                                    <div className="portal-p4e-mlt-item" style={checked ? { border: '1px solid #408de2' } : {}} >
                                                                        <div className="portal-p4e-mlt-chk" onClick={() => this.onCheck(col)}><Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@mf3s65@${col.id}`} checked={checked} /></div>
                                                                        <div className="portal-p4e-mlt-preview">
                                                                            <img className="portal-p4e-mlt-img" src={`/weaver/weaver.splitepage.transform.SptmForThumbnail?filerealpath=${col.filepath.substring(1)}&time=${Date.now()}`} onClick={e => this.imageCarousel(this, e)} alt="" />
                                                                        </div>
                                                                        {
                                                                            hasRight ? (
                                                                                    <div className="portal-p4e-mlt-opt">
                                                                                        <span className="portal-p4e-mlt-title">
                                                                                            {
                                                                                                col.id == file.id ? (
                                                                                                        edit ? (
                                                                                                                <input ref="input"
                                                                                                                  defaultValue={col.filename}
                                                                                                                  onClick={e => e.stopPropagation()}
                                                                                                                  onChange={this.onChange}
                                                                                                                  onKeyDown={(e) => {
                                                                                                                           e.stopPropagation();
                                                                                                                           if (e.keyCode == 13) {
                                                                                                                               this.onSave();
                                                                                                                           }
                                                                                                                       }}
                                                                                                                />
                                                                                                            ) : `${file.filename_new}.${col.filetype}`
                                                                                                    ) : `${col.filename}.${col.filetype}`
                                                                                            }
                                                                                        </span>
                                                                                        {
                                                                                            col.id == file.id && edit ? (
                                                                                                    <span className="portal-p4e-mlt-edit"
                                                                                                      onClick={(e) => {
                                                                                                              e.stopPropagation();
                                                                                                              this.onSave();
                                                                                                          }}
                                                                                                    >
                                                                                                        <i className="icon-coms-complete" title={getLabel(555, '完成')} />
                                                                                                    </span>
                                                                                                ) : (
                                                                                                    <span className="portal-p4e-mlt-edit"
                                                                                                      onClick={(e) => {
                                                                                                              e.stopPropagation();
                                                                                                              this.onEdit(col);
                                                                                                          }}
                                                                                                    >
                                                                                                        <i className="icon-coms-edit" title={getLabel(26473, '编辑')} />
                                                                                                    </span>
                                                                                                )
                                                                                        }
                                                                                        {
                                                                                            col.id == file.id && edit ? (
                                                                                                    <span className="portal-p4e-mlt-delete"
                                                                                                      onClick={(e) => {
                                                                                                              e.stopPropagation();
                                                                                                              this.onCancel();
                                                                                                          }}
                                                                                                    >
                                                                                                        <i className="icon-coms-Reset" title={getLabel(23757, '撤销')} />
                                                                                                    </span>
                                                                                                ) : (
                                                                                                    <span className="portal-p4e-mlt-delete"
                                                                                                      onClick={(e) => {
                                                                                                              e.stopPropagation();
                                                                                                              this.onDelete(col.id);
                                                                                                          }}
                                                                                                    >
                                                                                                        <i className="icon-coms-delete" title={getLabel(91, '删除')} />
                                                                                                    </span>
                                                                                                )
                                                                                        }
                                                                                    </div>
                                                                                ) : (
                                                                                    <div className="portal-p4e-mlt-opt">
                                                                                        <span className="portal-p4e-mlt-title2">{`${col.filename}.${col.filetype}`}</span>
                                                                                    </div>
                                                                                )
                                                                        }
                                                                    </div>
                                                                </li>
                                                            );
                                                        })
                                                    }
                                                </ul>
                                            ))
                                    }
                                    <div style={{ clear: 'both' }} />
                                    <div style={{ position: 'absolute', right: 0, margin: '10px' }}>
                                        <Pagination ecId={`${this && this.props && this.props.ecId || ''}_Pagination@uro54g`}
                                          showSizeChanger
                                          showQuickJumper
                                          current={pageCurrent}
                                          pageSize={pageSize}
                                          total={pageTotal}
                                          showTotal={total => `${getLabel(18609, '共')} ${total} ${getLabel(18256, '条')}`}
                                          pageSizeOptions={['10', '20', '50', '100']}
                                          onChange={this.onPageCurrentChange}
                                          onShowSizeChange={this.onPageSizeChange}
                                        />
                                    </div>
                                </div>
                            ) : (
                                <div className="ant-table-placeholder">
                                    <i className="anticon anticon-frown" />{getLabel(83553, '暂无数据')}
                                </div>
                            )
                    }
                </div>
            </div>
        );
    }

    onUploading(state) {
        if (state == 'uploading') {
            this.props.onLoading(true);
        } else if (state == 'uploaded') {
            this.props.onLoading(false);
        }
    }

    setPanelStatus(bool) {
        this.setState({
            isPanelShow: bool,
        });
    }

    initForm() {
        const { form } = this.state;
            WeaTools.callApi('/api/portal/materialLib/GetSearchConditionItems', 'POST', {}).then((result) => {
                    form.setCondition([result.conditioninfo]);
                    this.setState({
                        condition: result.conditioninfo,
                    });
            });
    }


    getTabButtonsAd() {
         const { form } = this.state;
        return [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0689bc`} type="primary" onClick={() => { this.getFiles(); this.setPanelStatus(false); }}>{getLabel(197, '搜索', 'label')}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s4rggh`} type="ghost" onClick={() => { form.resetForm(); this.updateInputValue(''); }}>{getLabel(2022, '重置', 'label')}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1o8mlx`} type="ghost" onClick={() => this.setPanelStatus(false)}>{getLabel(31129, '取消', 'label')}</Button>),
    ];
    }

    updateInputValue(v = '') {
        const { form } = this.state;
        this.setState({
            searchKey: v,
        });
        form.updateFields({
            filename: v,
        });
    }

    // getFilesKey = () => {
    //     const {form, searchKey } = this.state
    //     const params = form.getFormParams();
    //     params.word = searchKey;
    //     API.getWordLogKey(params).then((res) => {
    //         this.loading = false;
    //         if (res.stat us) {
    //             this.tableStore.getDatas(res.sessionkey);
    //             if (!this.title && res.title) {
    //                 this.title = res.title;
    //             }
    //         } else {
    //             message.error(res);
    //         }
    //     });
    // }


    getFiles(dir, pageCurrent, pageSize) {
        const { form } = this.state;
        const params = form.getFormParams();
        const { filename, uploaddate } = params;
        // console.log(typeof(uploaddate))
        // console.log(typeof(uploaddate)!='undefined')
        let _array = null;
        if (typeof (uploaddate) != 'undefined') {
            _array = $.parseJSON(JSON.stringify(uploaddate));
        }

        let array0 = '0';
        let startime = '';
        let endtime = '';
        if (_array != null) {
            array0 = _array[0];
        }
        if (array0 === '6') {
            startime = _array[1];
            endtime = _array[2];
        }

        // console.log(uploaddate[0],"====")
        this.props.onLoading(true);
        WeaTools.callApi('/api/portal/materialLib/getFiles', 'GET', {
            dir: dir || this.props.dir,
            pageCurrent: pageCurrent || this.state.pageCurrent,
            pageSize: pageSize || this.state.pageSize,
            filename,
            uploaddate: array0,
            startTime: startime,
            endTime: endtime,
        }).then((result) => {
            this.setState({
                data: result.data,
                pageTotal: result.count,
                checkedFiles: [],
                edit: false,
                file: {},
            });
            this.props.onLoading(false);
        });
    }

    onPageCurrentChange(pageCurrent) {
        this.setState({ pageCurrent });

        const { dir } = this.props;
        const { pageSize } = this.state;
        this.getFiles(dir, pageCurrent, pageSize);
    }

    onPageSizeChange(current, pageSize) {
        this.setState({ pageSize,
            pageCurrent: 1 });
        const { dir } = this.props;
        this.getFiles(dir, 1, pageSize);
    }

    onCheckAll(checked) {
        let { data = [] } = this.state;
        let checkedFiles = [];
        if (checked) {
            data.forEach((item) => {
                checkedFiles.push(item);
            });
        }
        this.setState({ checkedFiles });
    }

    onCheck(file) {
        const { multiCheck = false } = this.props;
        let { checkedFiles } = this.state;

        if (_.findIndex(checkedFiles, item => item.id == file.id) != -1) {
            _.remove(checkedFiles, item => item.id == file.id);
        } else if (multiCheck) {
                checkedFiles.push(file);
            } else {
                checkedFiles = [file];
            }

        this.setState({ checkedFiles });
    }

    onEdit(file = {}) {
        this.setState({ edit: true, file: { ...file, filename_new: file.filename } });
    }

    onChange(e) {
        const { file } = this.state;
        this.setState({ file: { ...file, filename_new: e.target.value } });
    }

    onSave() {
        const { file } = this.state;
        const { filename_new = '' } = file;

        if (filename_new.trim() == '') {
            message.warning(getLabel(15859, '必要信息不完整！'));
        } else if (!filename_new.toLowerCase().match(/^[0-9A-Za-z]+$/)) {
            message.warning(getLabel(387216, '文件名称只能包含字母和数字'));
        } else {
            this.props.onLoading(true);
            this.setState({ edit: false });
            WeaTools.callApi('/api/portal/materialLib/renameFile', 'POST', {
                ...file,
            }).then((result) => {
                if (result.api_status) {
                    message.success(getLabel(83885, '操作成功！'));
                    this.getFiles();
                } else {
                    message.warning(getLabel(83912, '操作失败！'));
                }
                this.props.onLoading(false);
            });
        }
    }

    onDelete(id) {
        Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel(15097, '确定要删除吗？'),
            onOk: () => {
                this.doDelete(id);
            },
        });
    }

    onBatchDelete() {
        const { checkedFiles = [] } = this.state;
        const chkIds = checkedFiles.map(item => item.id);
        const ids = chkIds.join(',');

        Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: getLabel(385625, '确定要删除选择的记录吗？'),
            onOk: () => {
                this.doDelete(ids);
            },
        });
    }

    doDelete(ids) {
        this.props.onLoading(true);
        WeaTools.callApi('/api/portal/materialLib/deleteFile', 'POST', { ids }).then((result) => {
            if (result.api_status) {
                message.success(getLabel(83885, '操作成功'));
                this.onPageCurrentChange(1);
            } else {
                message.warning(getLabel(83912, '操作失败'));
            }
            this.props.onLoading(false);
        });
    }

    onCancel() {
        this.setState({ edit: false, file: {} });
    }

    getCheckedFiles() {
        return this.state.checkedFiles;
    }
}

export default MaterialLibRight;
